import { createRouter, createWebHistory } from 'vue-router'
import store from '../store'
import { notification } from "ant-design-vue";

const routes = [
  {
    path: '/login',
    name: 'login',
    component: () => import('../views/LoginView.vue')
  }
  ,
  {
    path: '/',
    name: 'main',
    component: () => import('../views/MainView.vue'),
    // 给路由加个变量，后面根据此变量值判断该路由是否需要登录效验
    meta: {
      loginRequire: true
    },
    children: [{
      path: 'welcome',
      component: ()=> import('../views/main/Welcome.vue'), 
    },{
      path: 'passenger',
      component: ()=> import('../views/main/Passenger.vue'), 
    }]
  },
  {
    // 法务根路由的时候，会重定向到 /welcome 页面
    path: '',
    redirect: '/welcome'
  }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

// 路由登录拦截,beforeEach是路由跳转之前
// to是跳转到哪里，from 从哪里跳， next下一个执行
router.beforeEach((to, from, next) => {
  // 要不要对meta.loginRequire属性做监控拦截
  if (to.matched.some(function (item) {
    console.log(item, "是否需要登录校验：", item.meta.loginRequire || false);
    return item.meta.loginRequire
  })) {
    const _member = store.state.member;
    console.log("页面登录校验开始：", _member);
    if (!_member.token) {
      console.log("用户未登录或登录超时！");
      notification.error({ description: "未登录或登录超时" });
      next('/login');
    } else {
      next();
    }
  } else {
    next();
  }
});

export default router
